<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">学生获奖信息</span>
      </div>

      <pdf-preview :pdf-url="form.pdfUrl"></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">信息详情</span>
        </div>
        <div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="比赛名称" prop="competitionName" required>
              <el-input
                  v-model="form.competitionName"
                  placeholder="示例: 2014年学术杯子全国大学生数学建模竞赛"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="获奖学生" prop="awardStudents" required>
              <el-input
                  v-model="form.awardStudents"
                  placeholder="获奖的学生姓名，如张三李四"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="本人排名" prop="authorRank" required>
              <el-select v-model="form.authorRank" placeholder="请选择排名" style="width: 34vw;">
                <el-option
                    v-for="i in 10"
                    :key="i"
                    :label="i.toString()"
                    :value="i">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="获奖等级" prop="awardLevel" required>
              <el-input
                  v-model="form.awardLevel"
                  placeholder="如：一等奖"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="级别" prop="level" required>
              <el-input
                  v-model="form.level"
                  placeholder="如：国家级"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="授予单位" prop="grantingUnit" required>
              <el-input
                  v-model="form.grantingUnit"
                  placeholder="如：中国工业与应用数学学会"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="获奖时间" prop="awardTime" required>
              <el-date-picker
                  v-model="form.awardTime"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  style="width: 34vw;"
              ></el-date-picker>
            </el-form-item>

            <!-- 作者信息表格 -->
            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto;">
                <ul style="display: flex; list-style-type: none; padding: 0; margin: 0; line-height: 6vh; color: #3f3f3f">
                  <li style="margin-left: 1.5vw">排序</li>
                  <li style="margin-left: 3vw">姓名</li>
                  <li style="margin-left: 3.5vw">作者身份</li>
                  <li style="margin-left: 5vw">单位名称</li>
                </ul>

                <div v-for="(author, index) in form.authorInfo" :key="index" style="margin-top: 1vh; display: flex; align-items: center;">
                  <el-select style="width: 4vw;" v-model="author.rank" placeholder="排序">
                    <el-option
                        v-for="i in 10"
                        :key="i"
                        :label="i.toString()"
                        :value="i"
                    ></el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 5vw; margin-left: 1vw" placeholder="姓名"></el-input>

                  <el-select style="width: 5.5vw; margin-left: 1vw" v-model="author.identity" placeholder="身份">
                    <el-option label="老师" value="老师"></el-option>
                    <el-option label="博士生" value="博士生"></el-option>
                    <el-option label="硕士生" value="硕士生"></el-option>
                    <el-option label="本科生" value="本科生"></el-option>
                  </el-select>



                  <el-input v-model="author.institution" style="width: 15vw; margin-left: 3vw" placeholder="单位名称"></el-input>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="关联课题" prop="projectId">
              <el-input
                  v-model="form.projectId"
                  placeholder="请选择本ndnu-成果所属课题"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="备注信息" prop="remarks">
              <el-input
                  type="textarea"
                  v-model="form.remarks"
                  :rows="4"
                  placeholder="请输入备注信息"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>
          </el-form>

          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submitForm" class="upload-button" style="width: 10vw;">返 回</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {getStudentAwardById} from "@/api/result/awardStudent.js";
import {getProjectNameById} from "@/api/result/longitudinalProjects";
import PdfPreview from "@/components/result/PdfPreview.vue";

const route = useRoute()
const router = useRouter()
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  competitionName: '',
  awardStudents: '',
  authorRank: undefined,
  awardLevel: '',
  level: '',
  grantingUnit: '',
  awardTime: '',
  remarks: '',
  projectId: '',
  authorInfo: [{
    name: '',
    rank: 1,
    identity: '',
    institution: '',
    coFirstAuthor: false,
    corresponding: false
  }],
  syncStatus: '',
  pdfPath: ''
})

// 表单验证规则
const rules = {
  competitionName: [{ required: true, message: '请输入比赛名称', trigger: 'blur' }],
  awardStudents: [{ required: true, message: '请输入获奖学生', trigger: 'blur' }],
  authorRank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  awardLevel: [{ required: true, message: '请输入获奖等级', trigger: 'blur' }],
  level: [{ required: true, message: '请输入级别', trigger: 'blur' }],
  grantingUnit: [{ required: true, message: '请输入授予单位', trigger: 'blur' }],
  awardTime: [{ required: true, message: '请选择获奖时间', trigger: 'change' }]
}

// 添加作者
const addAuthor = () => {
  form.authorInfo.push({
    name: '',
    rank: form.authorInfo.length + 1,
    identity: '',
    institution: '',
    coFirstAuthor: false,
    corresponding: false
  })
}

// 删除作者
const removeAuthor = (index) => {
  form.authorInfo.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  router.push("/result/awardStudent");
}

// 安全转换日期为时间戳
const parseDateToTimestamp = (dateValue) => {
  if (!dateValue) return null;

  // 处理字符串格式日期（如"2025-08-13"）
  if (typeof dateValue === 'string') {
    const date = new Date(dateValue);
    return date.getTime(); // 转换为毫秒时间戳
  }

  // 处理数字类型时间戳
  if (typeof dateValue === 'number') {
    // 如果是秒级时间戳（10位数字），转换为毫秒级（13位）
    if (dateValue.toString().length === 10) {
      return dateValue * 1000;
    }
    return dateValue;
  }

  return null;
}

// 获取详情数据
onMounted(async () => {
  const id = route.query.id
  if (id) {
    try {
      const res = await getStudentAwardById(id)
      if (res.code === 200 && res.data) {
        const data = res.data
        // 修复时间显示问题：使用安全转换函数处理日期
        data.awardTime = parseDateToTimestamp(data.awardTime)

        // 处理获奖学生字符串
        if (typeof data.awardStudents === 'string') {
          try {
            data.awardStudents = JSON.parse(data.awardStudents)
          } catch (e) {
            console.error('解析获奖学生数据失败:', e)
          }
        }
        Object.assign(form, data)
      } else {
        ElMessage.error('获取学生获奖信息失败')
      }
    } catch (error) {
      console.error('获取学生获奖信息失败:', error)
      ElMessage.error('获取学生获奖信息失败，请重试')
    }

  }
})
</script>

<style scoped>
.upload-button {
  color: white;
  height: 3.8vh;
  width: 6.5vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
}

.upload-button:hover {
  background-color: #009b77;
}

canvas {
  display: block;
  margin: 0 auto;
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}
</style>
